<template>
  <div class="project-interface-group-mnt layout flex-col">
    <div class="top">
      <div class="left">
        <a-button type="primary" @click="addBtnClick()">
          <a-icon type="plus"/>
          添加
        </a-button>

        <a-button type="primary" @click="editBtnClick()" :disabled="this.rowId == ''">
          <a-icon type="edit"/>
          编辑
        </a-button>
        <a-button type="primary" @click="removeBtnClick()" :disabled="this.selectedRowKeys.length < 1">
          <a-icon type="delete"/>
          删除
        </a-button>
        <a-button type="primary" @click="onSearch()">
          <a-icon type="redo"/>
          刷新
        </a-button>
        <a-button type="primary" icon="arrow-up" :disabled="rowId == ''" @click="moveUp()">上移</a-button>
        <a-button type="primary" icon="arrow-down" :disabled="rowId == ''" @click="moveDown()">下移</a-button>
      </div>
    </div>
    <a-table
      v-if="treeForm && treeForm.length"
      style="overflow-y: auto;height:84%"
      rowKey="id"
      bordered
      :columns="columns"
      :data-source="treeForm"
      :rowSelection="rowSelection"
      :defaultExpandAllRows="true"
      :pagination="false"
      :rowClassName="setRowClassName"
      :customRow="customRow"
    >
      <span slot-scope="text, row" slot="name">
        <a @click.stop.prevent="handlerGoToFormDetail(row)" class="a-edit">{{ text }}</a>
      </span>
      <span slot="modifyTime" slot-scope="text">{{ moment(text).format('YYYY/MM/DD HH:mm:ss') }}</span>
    </a-table>

  </div>
</template>

<script>
  import {getColumns} from '@/api/tableColumns'
  import projectManageService from '@/api/projectManageService'
  import moment from 'moment'

  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      scopedSlots: {
        customRender: 'name'
      }
    },
    {
      title: '修改时间',
      width: '15%',
      dataIndex: 'modifyTime',
      scopedSlots: {customRender: 'modifyTime'}
    }
  ]
  export default {
    name: 'ProjectInterfaceGroup',
    data() {
      return {
        treeForm: [],
        activeKey: '',
        columns,
        showId: false,
        selectedRows: [],
        selectedRowKeys: [],
        activeId: [],
        rowId: ''
      }
    },
    props: {
      project: {
        type: Object,
        default: () => ({})
      },
      type: {
        type: String,
        default: ''
      }
    },
    created() {
      this.projectInterfaceGroupList();
    },
    methods: {
      moment,
      setRowClassName(record) {
        const isActiveId = this.activeId.some((item) => item === record.id)
        if (isActiveId) {
          return 'rowcolor'
        }
      },
      customRow(record, index) {
        return {
          style: {
            // 行背景色
            'background-color': record.id === this.rowId ? 'rgb(230, 247, 255)' : 'white'
          },
          on: {
            click: () => {
              this.rowId = record.id
            },
            dblclick: () => {

            }
          }
        }
      },
      moveUpFun(list = [], id = '') {
        const index = list.findIndex((item) => item.id === id)
        const row = list[index]
        if (index === 0) {
          this.$message.error('已经是第一行，不能上移')
          return false
        } else {
          const lastId = list[index - 1].id
          list.splice(index - 1, 0, row)
          list.splice(index + 1, 1)
          return {lastId: lastId, list: list}
        }
      },
      moveDownFun(list = [], id = '') {
        const index = list.findIndex((item) => item.id === id)
        const row = list[index]
        if (index === list.length - 1) {
          this.$message.error('已经是最后一行，不能下移')
          return false
        } else {
          const nextId = list[index + 1].id
          list.splice(index + 2, 0, row)
          list.splice(index, 1)
          return {nextId: nextId, list: list}
        }
      },
      moveUp() {
        const businessFormId = this.rowId
        const obj = this.moveUpFun(this.treeForm, businessFormId)
        if (obj) {
          this.treeForm = obj.list
        }
      },
      moveDown() {
        const businessFormId = this.rowId
        const obj = this.moveDownFun(this.treeForm, businessFormId)
        if (obj) {
          this.treeForm = obj.list
        }
      },
      addBtnClick() {
        this.showEditDialog({}, false)
      },
      editBtnClick() {
        const treeArray = this.treeToArray(this.treeForm);
        const row = treeArray.find((item) => item.id === this.rowId);
        if (row === undefined || row === '' || row === null) {
          this.$message.error('请选择一行数据!')
        }
        projectManageService.projectInterfaceGroupGet({interfaceGroupId: row.id}).then((d) => {
          if (!d) {
            this.$message.error('项目接口分组：【' + this.row.groupName + '】已被删除！')
          } else {
            this.showEditDialog(d, true);
          }
        })
      },
      // reduce实现
      treeToArray(tree) {
        return tree.reduce((res, item) => {
          const {children, ...i} = item
          return res.concat(i, children && children.length ? this.treeToArray(children) : [])
        }, [])
      },
      removeBtnClick() {
        this.$confirm({
          content: '确认删除项目接口分组？',
          okType: 'danger',
          onOk: () => {
            projectManageService.projectInterfaceGroupDelete({interfaceGroupId: this.selectedRowKeys}).then((d) => {
              if (d) {
                this.projectInterfaceGroupList();
                this.$message.success('删除成功!')
              } else {
                debugger;
                this.$message.error('删除失败!')
              }
            })
          }
        })
      },
      showEditDialog(projectInterfaceGroup, update) {
        projectInterfaceGroup = projectInterfaceGroup || {};
        let title = (projectInterfaceGroup.id ? '编辑' : '添加') + '项目接口分组';
        this.$dialog({
          title: title,
          content: () => import('@/views/investmentOnline/interfaceManage/dialog/ProjectInterfaceGroupFormCtl'),
          width: 600,
          centered: true,
          maskClosable: false,
          validateContent: true,
          props: {
            project: this.project,
            data: projectInterfaceGroup
          },
          on: {
            ok: (dialog) => {
              let data = dialog.getDialogCtl().getData();
              data.projectId = this.project.id;
              this.saveProjectInterfaceGroup(data, update);
              dialog.closeDialog();
            },
            cancel() {
            }
          }
        })
      },
      saveProjectInterfaceGroup(projectInterfaceGroup, update) {
        if (update && projectInterfaceGroup !== undefined
          && projectInterfaceGroup !== null
          && projectInterfaceGroup.id !== undefined
          && projectInterfaceGroup.id !== null
          && projectInterfaceGroup.id !== '') {
          projectManageService.projectInterfaceGroupUpdate(projectInterfaceGroup).then(
            (d) => {
              this.$message.success('更新成功!');
              this.projectInterfaceGroupList();
            },
            (e) => {
              this.$message.error('更新失败!');
            }
          )
        } else {
          projectManageService.projectInterfaceGroupSave(projectInterfaceGroup).then(
            (d) => {
              this.$message.success('保存成功!');
              this.projectInterfaceGroupList();
            },
            (e) => {
              this.$message.error('保存失败!');
            }
          )
        }
      },
      switchToBoolean(projectInterface) {
        const arr = Object.assign({}, projectInterface);
        arr.enable = !!projectInterface.enable;
        return arr;
      },
      handlerGoToFormDetail(record) {
        if (record === undefined || record === '' || record === null) {
          this.$message.error('请选择一行数据!')
        }
        projectManageService.projectInterfaceGroupGet({interfaceGroupId: record.id}).then((d) => {
          if (!d) {
            this.$message.error('项目接口分组：【' + this.row.groupName + '】已被删除！')
          } else {
            this.showEditDialog(d, true);
          }
        })
      },
      projectInterfaceGroupList() {
        let queryParams = {
          projectId: this.project.id,
          loadInterface: false
        }
        projectManageService.projectInterfaceGroupQuery(queryParams).then(
          (d) => {
            this.treeForm = d;
            this.groupPaths = d;
          },
          (e) => {
          }
        )
      },
      onSearch() {
        this.projectInterfaceGroupList();
      }
    },
    watch: {},
    computed: {
      rowSelection() {
        return {
          selectedRowKeys: this.selectedRowKeys,
          onChange: (selectedRowKeys, selectedRows) => {
            if (this.selectedRows.length > 0) {
              const key = '_rowKey';
              this.selectedRowKeys = [selectedRowKeys.filter(item => item !== this.selectedRowKeys[0])[0]];
              this.selectedRows = [selectedRows.filter(item => item[key] !== this.selectedRows[0][key])[0]];
            } else {
              this.selectedRowKeys = [selectedRowKeys[0]];
              this.selectedRows = [selectedRows[0]];
            }
          }
        }
      }
    },
  }
</script>

<style lang="less" scoped>
  .project-interface-group-mnt {
    .left {
      .ant-btn {
        margin: 0px 10px 10px 0px
      }
    }
  }
</style>
